//
//  DDHeadLine.m
//  NetEaseNews
//
//  Created by dqw on 15/7/24.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "DDHeadLine.h"
#import <objc/runtime.h>
#import "DDNetworkTool.h"


@implementation DDHeadLine

- (instancetype)initWithDic:(NSDictionary *)dic
{
    if (self = [super init]) {
        
        for (NSString *propertyName in [self getProperties]) {
            [self setValue:dic[propertyName] forKey:propertyName];
        }
    }
    return self;
}
+ (instancetype)headLineWithDic:(NSDictionary *)dic
{
    return [[self alloc]initWithDic:dic];
}

+ (void)headLinesWithCompletionB:(void(^)(NSArray *))completionB
{
    NSAssert(completionB, @"completionB不能为nil");
    [DDNetworkTool sharedTool].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [[DDNetworkTool sharedTool]GET:@"ad/headline/0-4.html" parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *dict) {
        NSString *firstKey = dict.keyEnumerator.nextObject;
        NSArray *arr = dict[firstKey];
        NSMutableArray *arrM = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            DDHeadLine *headline = [DDHeadLine headLineWithDic:dic];
            [arrM addObject:headline];
            }
        if (completionB) {
            completionB(arrM.copy);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (NSArray *)getProperties
{
    unsigned int count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    NSMutableArray *mArr = [[NSMutableArray alloc]initWithCapacity:count];
    
    for (int i = 0; i < count; i++) {
        objc_property_t property = properties[i];
        const char *nameC = property_getName(property);
        NSString *nameOC = [NSString stringWithCString:nameC encoding:NSUTF8StringEncoding];
        [mArr addObject:nameOC];
    }
    return mArr;
    
}
@end
